package com.oracle.service.impl;

import com.oracle.compents.ApiResponse;
import com.oracle.entity.LoginTeacher;
import com.oracle.mapper.TeacherMapper;
import com.oracle.pojo.Teacher;
import com.oracle.service.LoginTeacherService;
import com.oracle.util.JJWTUtilsTeacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Service
public class LoginTeacherServiceImpl implements LoginTeacherService {

    /**
     * 认证管理器
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private TeacherMapper teacherMapper;


    @Override
    public ApiResponse login(Teacher teacher) {
        //通过UsernamePasswordAuthenticationToken获取用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(teacher.getTeachNum(),teacher.getTeachPwd());

        //AuthenticationManager委托机制对authenticationToken 进行用户认证  底层调用TeacherDetailsServiceImpl
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //如果认证没有通过，给出对应的提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("认证失败");
        }

        //如果认证通过，使用user生成jwt  jwt存入ResponseResult 返回

        //如果认证通过，拿到这个当前登录用户信息
        LoginTeacher loginTeacher = (LoginTeacher) authenticate.getPrincipal();

        //脱敏
        loginTeacher.getTeacher().setTeachPwd(null);


        String teachNum = loginTeacher.getTeacher().getTeachNum();
             System.out.println(teachNum);


        String jwt = JJWTUtilsTeacher.getJwtToken(loginTeacher.getTeacher());

        //把完整的用户信息存入redis  userid为key   用户信息为value
        stringRedisTemplate.opsForValue().set("login:user:"+teacher.getTeachNum(),jwt);
        stringRedisTemplate.expire("login:user:"+teacher.getTeachNum(),3, TimeUnit.HOURS);//设置失效时间
        return ApiResponse.success(jwt);
    }

    @Override
    public void register(Teacher teacher) {
        teacherMapper.insert(teacher);
    }

    @Override
    public void loginOut(Teacher teacher) {
        //把用户登录信息 删除 即退出
        stringRedisTemplate.delete("login:user:" +teacher.getTeachNum());
    }

}
